//
//  WDGrabOrdersPersonInfoViewController.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/8/13.
//

#import "WDGrabOrdersPersonInfoViewController.h"
#import "WDGrabOrdersPersonInfoViewModel.h"
//#import "WDGrabOrdersPersonInfoTopView.h"
#import "WDCancelWorkOrderBottomView.h"
#import "WDGrabOrdersPersonInfoTextView.h"
#import "WDGrabOrdersPersonInfoLabelView.h"
#import "WDGrabOrdersAddressTextView.h"
#import "TYZBasePickerView.h"
#import "WDGrabOrderPersonCarInfoView.h" // 车辆信息

@interface WDGrabOrdersPersonInfoViewController () <UIGestureRecognizerDelegate>
@property (nonatomic, strong) WDGrabOrdersPersonInfoViewModel *viewModel;

//@property (nonatomic, strong) WDGrabOrdersPersonInfoTopView *topView;

/// 抢单人
@property (nonatomic, strong) WDGrabOrdersPersonInfoTextView *grabPersonView;

/// 联系电话
@property (nonatomic, strong) WDGrabOrdersPersonInfoTextView *phoneView;

/// 实际救援地址
@property (nonatomic, strong) WDGrabOrdersAddressTextView *rescueAdsView;

/// 预计里程
@property (nonatomic, strong) WDGrabOrdersPersonInfoTextView *expectMileageView;

/// 预计到达时间
@property (nonatomic, strong) WDGrabOrdersPersonInfoLabelView *arrivalTimeView;


@property (nonatomic, strong) WDCancelWorkOrderBottomView *bottomView;

/// 选择
@property (nonatomic, strong) TYZBasePickerView *pickerView;

/// 车辆信息
@property (nonatomic, strong) WDGrabOrderPersonCarInfoView *carInfoView;


@end

@implementation WDGrabOrdersPersonInfoViewController

- (void)dealloc
{
    debugMethod();
}

- (void)initWithVar {
    [super initWithVar];
    
}

- (void)initWithViewModel {
    _viewModel = [WDGrabOrdersPersonInfoViewModel new];
    _viewModel.serviceModel = self.serviceModel;
    [_viewModel setupData];
    
}


- (void)initWithNavBar {
    [super initWithNavBar];
    
    [self initWithBackButton];
    self.navigationItem.title = self.viewModel.title;
}

- (void)initWithSubView {
    [super initWithSubView];
    
    [self initWithRootContent:NO];
    self.rootContent.height = self.rootContent.height - TABBAR_HEIGHT;
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F8F8F8"];
    self.rootContent.backgroundColor = [UIColor colorWithHexString:@"#F8F8F8"];
    
//    [self initWithTopView];
    
    [self initWithUI];
    
    @weakify(self);
    [self.viewModel setupReqApplyModel:^{
        @strongify(self);
        [self initWithUI];
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return NO;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)initWithUI {
    // 抢单人
    [self initWithGrabPersonView];
    
    // 联系电话
    [self initWithPhoneView];
    
    // 实际救援地址
    [self initWithRescueAdsView];
    
    /// 预计里程
    [self initWithExpectMileageView];
    
    // 预计到达时间
    [self initWithArrivalTimeView];
    
    [self initWithBottomView];
    
    [self initWithPickerView];
    
    [self initWithCarInfoView];
}

- (void)clickedBack:(id)sender {
    [SVProgressHUD showWithStatus:@"取消锁定中..."];
//    @weakify(self);
    [self.viewModel requestWithGrabLock:^(EDSRespondDataEntity * _Nonnull respond) {
//        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"取消锁定成功！";
            }
            [SVProgressHUD showSuccessWithStatus:tip];
            [super clickedBack:sender];
        } else {
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"取消锁定失败，请稍后再试！";
            }
            [SVProgressHUD showInfoWithStatus:tip];
            if (respond.code == 400) {
                [super clickedBack:sender];
            }
        }
    }];
}

/// 抢单人
- (void)initWithGrabPersonView {
    if (!_grabPersonView) {
        CGRect frame = CGRectMake(0, 10, kScreenW, kWDGrabOrdersPersonInfoTextViewHeight);
        _grabPersonView = [[WDGrabOrdersPersonInfoTextView alloc] initWithFrame:frame];
        _grabPersonView.title = @"抢单人";
        _grabPersonView.placeholder = @"请输入抢单人姓名";
        _grabPersonView.isRequired = YES;
        [self.rootContent addSubview:_grabPersonView];
        RAC(self.viewModel.reqApplyModel, rescueEngineerName) = self.grabPersonView.valueTxtField.rac_textSignal;
    }
    _grabPersonView.valueTxtField.text = objectNull(self.viewModel.reqApplyModel.rescueEngineerName);
}

/// 联系电话
- (void)initWithPhoneView {
    if (!_phoneView) {
        CGRect frame = _grabPersonView.frame;
        frame.origin.y = _grabPersonView.bottom;
        _phoneView = [[WDGrabOrdersPersonInfoTextView alloc] initWithFrame:frame];
        _phoneView.title = @"联系电话";
        _phoneView.placeholder = @"请输入联系电话";
        _phoneView.isRequired = YES;
        [self.rootContent addSubview:_phoneView];
        RAC(self.viewModel.reqApplyModel, rescueEngineerPhone) = self.phoneView.valueTxtField.rac_textSignal;
    }
    _phoneView.valueTxtField.text = objectNull(self.viewModel.reqApplyModel.rescueEngineerPhone);
}

/// 实际救援地址
- (void)initWithRescueAdsView {
    if (!_rescueAdsView) {
        CGRect frame = _grabPersonView.frame;
        frame.origin.y = _phoneView.bottom;
        _rescueAdsView = [[WDGrabOrdersAddressTextView alloc] initWithFrame:frame];
        _rescueAdsView.title = @"实际救援地址";
        _rescueAdsView.placeholder = @"请输入地址";
        _rescueAdsView.isRequired = YES;
//        _rescueAdsView.valueTxtField.text = @"济南市历城区港沟街道中铁银座";
//        _rescueAdsView.valueColor = [UIColor colorWithHexString:@"#59D8C6"];
        [self.rootContent addSubview:_rescueAdsView];
        RAC(self.viewModel.reqApplyModel, rescueAddress) = self.rescueAdsView.valueTxtField.rac_textSignal;
        @weakify(self);
        _rescueAdsView.touchEndEditBlock = ^{
            @strongify(self);
            [self getLonLatAddress:self.rescueAdsView.valueTxtField.text];
        };
    }
    self.rescueAdsView.valueTxtField.text = objectNull(self.viewModel.reqApplyModel.rescueAddress);
}

/// 预计里程
- (void)initWithExpectMileageView {
    if (!_expectMileageView) {
        CGRect frame = _grabPersonView.frame;
        frame.origin.y = _rescueAdsView.bottom;
        _expectMileageView = [[WDGrabOrdersPersonInfoTextView alloc] initWithFrame:frame unit:@"km"];
        _expectMileageView.title = @"预计里程";
        _expectMileageView.placeholder = @"请输入";
        _expectMileageView.isRequired = YES;
        _expectMileageView.enabled = YES;
//        _expectMileageView.valueTxtField.text = @"35km";
//        _expectMileageView.valueColor = [UIColor colorWithHexString:@"#59D8C6"];
        [self.rootContent addSubview:_expectMileageView];
    }
    double distance = self.viewModel.reqApplyModel.estimateDistance / 1000.0;
    self.expectMileageView.valueTxtField.text = [NSString stringWithFormat:@"%.2f", distance];
}

/// 预计到达时间
- (void)initWithArrivalTimeView {
    if (!_arrivalTimeView) {
        CGRect frame = _grabPersonView.frame;
        frame.origin.y = _expectMileageView.bottom;
        _arrivalTimeView = [[WDGrabOrdersPersonInfoLabelView alloc] initWithFrame:frame];
        _arrivalTimeView.hiddenBottomLine = YES;
        _arrivalTimeView.title = @"预计到达时间";
        _arrivalTimeView.isRequired = YES;
        [self.rootContent addSubview:_arrivalTimeView];
        @weakify(self);
        _arrivalTimeView.viewBlock = ^(id  _Nullable data) {
            @strongify(self);
            [self actionWithChooseArrivalTime];
        };
    }
}

/// 选项
- (void)initWithPickerView {
    CGRect frame = CGRectMake(0, kScreenH - kTYZBasePickerViewHeight, kScreenW, kTYZBasePickerViewHeight);
    _pickerView = [[TYZBasePickerView alloc] initWithFrame:frame];
    @weakify(self);
    _pickerView.viewBlock = ^(id  _Nullable data) {
        @strongify(self);
//        debugLog(@"data=%@", data);
        self.arrivalTimeView.value = data;
        self.arrivalTimeView.valueColor = [UIColor colorWithHexString:@"#333333"];
        self.viewModel.reqApplyModel.estimateArrivalTime = data;
    };
}

- (void)initWithBottomView {
    CGRect frame = CGRectMake(0, self.rootContent.bottom, kScreenW, TABBAR_HEIGHT);
    _bottomView = [[WDCancelWorkOrderBottomView alloc] initWithFrame:frame];
    _bottomView.btnTitle = @"确认";
    [self.view addSubview:_bottomView];
        @weakify(self);
    _bottomView.viewBlock = ^(id  _Nullable data) {
        @strongify(self);
        [self actionWithSubmit];
    };
}

/// 车辆信息
- (void)initWithCarInfoView {
    if (!_carInfoView) {
        CGRect frame = CGRectMake(0, self.arrivalTimeView.bottom + 10, kScreenW, kWDGrabOrderPersonCarInfoViewHeight);
        _carInfoView = [[WDGrabOrderPersonCarInfoView alloc] initWithFrame:frame];
        [self.rootContent addSubview:_carInfoView];
    }
    if (self.viewModel.serviceModel) {
        [self.carInfoView updateWithViewData:self.viewModel.serviceModel];
    }
}

/// 根据地址获取经纬度
/// - Parameter ads: ads description
- (void)getLonLatAddress:(NSString *)ads {
    @weakify(self);
    debugLog(@"ads=%@", ads);
    [[WDLocationManager shareInstance] geocodeSearchAds:ads completion:^(CGFloat latitude, CGFloat longitude) {
        @strongify(self);
        self.viewModel.reqApplyModel.rescueLatitude = latitude;
        self.viewModel.reqApplyModel.rescueLongitude = longitude;
        [self getTwoPointDistance:latitude longitude:longitude];
    }];
}

/// 计算两点的距离
/// - Parameters:
///   - latitude: latitude description
///   - longitude: longitude description
- (void)getTwoPointDistance:(CGFloat)latitude longitude:(CGFloat)longitude {
    @weakify(self);
    [self.viewModel calcTwoPointDistance:^{
        @strongify(self);
        CGFloat km = self.viewModel.reqApplyModel.estimateDistance / 1000.0;
        NSString *str = [NSString stringWithFormat:@"%.2f", km];
        self.expectMileageView.valueTxtField.text = str;
    }];
    
    /*
    AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:latitude longitude:longitude];
    AMapGeoPoint *endPoint = [AMapGeoPoint locationWithLatitude:self.viewModel.serviceModel.rescueLatitude longitude:self.viewModel.serviceModel.rescueLongitude];
//    @weakify(self);
    [[WDLocationManager shareInstance] getTwoPointDistance:startPoint end:endPoint completion:^(NSInteger distance) {
        @strongify(self);
//        debugLog(@"distance=%zd", distance);
        CGFloat km = distance / 1000.0;
        NSString *str = [NSString stringWithFormat:@"%.2fkm", km];
//        debugLog(@"str=%@", str);
        self.expectMileageView.valueTxtField.text = str;
    }];
    */
}

/// 选择预计到达时间
- (void)actionWithChooseArrivalTime {
    [_pickerView updateWithViewData:self.viewModel.arrivalTimeOptions];
    [_pickerView show];
}

/// 确认
- (void)actionWithSubmit {
    
//    [[WDLocationManager shareInstance] geocodeSearchAds:@"济南市天桥区泺口街道泺口齐鲁内衣城" completion:^(CGFloat latitude, CGFloat longitude) {
//            
//    }];
    
    NSString *rescueEngineerName = objectNull(self.viewModel.reqApplyModel.rescueEngineerName);
    if ([rescueEngineerName isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入抢单人姓名！"];
        return;
    }
    if (rescueEngineerName.length > 40) {
        [SVProgressHUD showInfoWithStatus:@"您输入的抢单人超过40个字！"];
        return;
    }
    NSString *rescueEngineerPhone = objectNull(self.viewModel.reqApplyModel.rescueEngineerPhone);
    if ([rescueEngineerPhone isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入抢单人手机号！"];
        return;
    }
    
    if (rescueEngineerPhone.length != 11) {
        [SVProgressHUD showInfoWithStatus:@"请输入11位抢单人手机号！"];
        return;
    }
    
    
    
    // rescueAddress
    if ([objectNull(self.viewModel.reqApplyModel.rescueAddress) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入实际救援地址！"];
        return;
    }
    
    // estimateDistance
    if (self.viewModel.reqApplyModel.estimateDistance <= 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入预计里程！"];
        return;
    }
    
    // estimateArrivalTime
    if ([objectNull(self.viewModel.reqApplyModel.estimateArrivalTime) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入选择预计到达时间！"];
        return;
    }
    
    @weakify(self);
    [SVProgressHUD showWithStatus:@"提交中......"];
    [self.viewModel requestWithApply:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"提交成功！";
            }
            [SVProgressHUD showSuccessWithStatus:tip];
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"提交失败，请稍后再试！";
            }
            [SVProgressHUD showInfoWithStatus:tip];
        }
    }];
}

@end
